<template>
  <div class="inline-flex items-center space-x-2">
    <!-- 验证码显示区域 -->
    <div 
      ref="captchaRef"
      class="relative w-32 h-10 bg-gray-50 rounded border select-none cursor-pointer"
      @click.prevent="refreshCode"
    >
      <!-- 干扰线 -->
      <canvas 
        ref="canvasRef"
        class="absolute inset-0 w-full h-full"
      ></canvas>
      
      <!-- 数字显示 -->
      <div class="relative flex items-center justify-center h-full">
        <span 
          v-for="(digit, index) in code" 
          :key="index"
          class="text-2xl font-bold"
          :style="{
            color: getRandomColor(),
            transform: `rotate(${getRandomRotate()}deg)`,
            marginLeft: index ? '4px' : '0'
          }"
        >
          {{ digit }}
        </span>
      </div>
    </div>

    <!-- 刷新按钮 -->
    <el-button @click.prevent="refreshCode" title="刷新验证码" type="primary">Refresh</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'CaptchaCode',
  components: {
    Refresh
  },
  props: {
    // 验证码长度
    length: {
      type: Number,
      default: 4
    }
  },
  emits: ['update:code'],
  setup(props, { emit }) {
    const code = ref('')
    const canvasRef = ref<HTMLCanvasElement | null>(null)
    const captchaRef = ref<HTMLDivElement | null>(null)

    // 生成随机数字
    const generateCode = () => {
      let newCode = ''
      for (let i = 0; i < props.length; i++) {
        newCode += Math.floor(Math.random() * 10)
      }
      code.value = newCode
      emit('update:code', newCode)
    }

    // 获取随机颜色
    const getRandomColor = () => {
      const colors = [
        '#1890ff',
        '#52c41a',
        '#722ed1',
        '#fa8c16',
        '#eb2f96',
        '#faad14'
      ]
      return colors[Math.floor(Math.random() * colors.length)]
    }

    // 获取随机旋转角度
    const getRandomRotate = () => {
      return Math.random() * 30 - 15
    }

    // 绘制干扰线
    const drawLines = () => {
      const canvas = canvasRef.value
      const ctx = canvas?.getContext('2d')
      if (!canvas || !ctx) return

      const width = canvas.width
      const height = canvas.height

      // 清空画布
      ctx.clearRect(0, 0, width, height)

      // 绘制干扰线
      for (let i = 0; i < 6; i++) {
        ctx.beginPath()
        ctx.moveTo(Math.random() * width, Math.random() * height)
        ctx.lineTo(Math.random() * width, Math.random() * height)
        ctx.strokeStyle = getRandomColor()
        ctx.lineWidth = 1
        ctx.stroke()
      }

      // 绘制干扰点
      for (let i = 0; i < 30; i++) {
        ctx.beginPath()
        ctx.arc(
          Math.random() * width,
          Math.random() * height,
          1,
          0,
          2 * Math.PI
        )
        ctx.fillStyle = getRandomColor()
        ctx.fill()
      }
    }

    // 刷新验证码
    const refreshCode = () => {
      generateCode()
      drawLines()
    }

    // 初始化canvas大小
    const initCanvas = () => {
      const canvas = canvasRef.value
      const container = captchaRef.value
      if (!canvas || !container) return

      canvas.width = container.clientWidth
      canvas.height = container.clientHeight
    }

    // 组件挂载后初始化
    onMounted(() => {
      initCanvas()
      refreshCode()

      // 监听窗口大小变化，重新设置canvas大小
      window.addEventListener('resize', initCanvas)
    })

    return {
      code,
      canvasRef,
      captchaRef,
      getRandomColor,
      getRandomRotate,
      refreshCode
    }
  }
})
</script>